<template>
  <div class="page-container hide-scrollbar" ref="pageContainer">

    <div class="article-summary" v-for="summary in displayedSummaries" :key="summary.month" ref="summaryContainers">
      <div class="month-header" v-if="summary.articles.length > 0">
        <div class="month-divider"></div>
        <div class="month-text">{{ formatMonthDisplay(summary.month) }}</div>
        <div class="month-divider"></div>
      </div>
      <div class="article-grid">
        <div class="article-card" v-for="item in summary.articles" :key="`${summary.month}-${item.id}`"
          @click="getArticleDetailsData(item.id)">
          <div class="article-image-wrapper">
            <div class="article-img" :style="{ backgroundImage: 'url(' + item.cover + ')' }">
              <div class="image-overlay"></div>
            </div>
            <div class="article-category">阅读</div>
          </div>
          <div class="article-content">
            <div class="article-title">{{ item.title }}</div>
            <div class="article-author">{{ item.subtitle }}</div>
            <div class="article-footer">
              <div class="read-more">阅读更多</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div v-if="isLoading" class="loading">加载中...</div>

    <!-- 使用ReadingDetail子组件 -->
    <ReadingDetail :articleId="articleId" :isVisible="isDetailsVisible" @close="closeArticleDetails"
      @article-change="handleArticleChange" />

  </div>
</template>

<script>
import { getReadingListByMonth } from '@/api/api'
import ReadingDetail from '@/components/ReadingDetail.vue'
import { mapActions } from 'vuex'

export default {
  name: 'NotePage',
  components: {
    ReadingDetail
  },
  data() {
    return {
      allSummaries: [],// 存储所有月份的数据
      displayedSummaries: [],// 显示在页面上的月份数据
      currentEarliestMonth: '',// 当前加载到的最早月份
      isLoading: false, // 是否正在加载中
      loadLock: false,// 防止重复加载的锁
      articleId: '',// 记录文章id
      isDetailsVisible: false // 控制详情页显示/隐藏
    }
  },
  created() {
    // 初始化全局音频实例
    this.initAudio()
    // 初始化：获取当前月份及前两个月
    const months = this.getRecentMonths(3);
    this.currentEarliestMonth = months[months.length - 1];

    // 加载初始的3个月份数据
    months.forEach(month => {
      this.loadMonthData(month);
    });
  },
  mounted() {
    // 监听滚动事件，实现滚动加载
    this.$refs.pageContainer.addEventListener('scroll', this.handleScroll);
    // 检查路由参数，如果存在 articleId，则自动打开详情
    this.checkRouteQuery();
  },
  beforeDestroy() {
    // 移除滚动监听
    this.$refs.pageContainer.removeEventListener('scroll', this.handleScroll);
  },
  methods: {
    // 映射音频store的actions
    ...mapActions('audio', ['initAudio', 'togglePlay', 'pauseAudio']),

    // 切换阅读文章音频播放/暂停
    toggleArticleAudio() {
      if (!this.articleDetailsData?.audio) return
      const audioInfo = {
        id: this.articleDetailsData?.id || this.articleId,
        audio_url: this.articleDetailsData.audio
      }
      this.togglePlay(audioInfo)
    },

    // 音频时间格式化 mm:ss
    formatAudioTime(seconds) {
      const sec = isFinite(seconds) && seconds >= 0 ? Math.floor(seconds) : 0
      const m = Math.floor(sec / 60)
      const s = sec % 60
      return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`
    },
    // 获取最近count个月份
    getRecentMonths(count) {
      const months = [];
      const today = new Date();

      for (let i = 0; i < count; i++) {
        const year = today.getFullYear();
        // 计算月份
        let month = today.getMonth() + 1 - i;

        // 处理跨年情况
        if (month <= 0) {
          month += 12;
          today.setFullYear(year - 1);
        }

        const monthStr = `${year}-${month.toString().padStart(2, '0')}`;
        months.push(monthStr);
      }

      return months;
    },

    // 根据传入的月份，计算并返回前一个月
    getPreviousMonth(month) {
      const [year, monthNum] = month.split('-').map(Number);
      let prevYear = year;
      let prevMonth = monthNum - 1;

      if (prevMonth < 1) {
        prevMonth = 12;
        prevYear--;
      }

      return `${prevYear}-${prevMonth.toString().padStart(2, '0')}`;
    },

    loadMonthData(month) {
      // 检查是否已加载过该月份数据
      if (this.allSummaries.some(item => item.month === month)) {
        return;
      }

      this.isLoading = true;
      getReadingListByMonth(month)
        .then(res => {
          // 存储所有月份数据
          this.allSummaries.push({
            month,
            articles: res.data
          });

          // 更新显示的数据（保持顺序）
          this.displayedSummaries = [...this.allSummaries]
            .sort((a, b) => b.month.localeCompare(a.month));
        })
        .catch(err => {
          console.error(`加载${month}数据失败:`, err);
        })
        .finally(() => {
          this.isLoading = false;
          this.loadLock = false;
        });
    },

    // 转换月份格式
    formatMonthDisplay(month) {
      const monthNum = month.split('-')[1];
      // 去除前导零
      return `${parseInt(monthNum)}月`;
    },

    // 监听滚动事件，判断是否滚动到接近底部，触发加载更多月份数据
    handleScroll() {
      // 如果正在加载中或已加锁，不执行
      if (this.isLoading || this.loadLock) return;

      const container = this.$refs.pageContainer;
      const lastSummary = this.$refs.summaryContainers?.[this.$refs.summaryContainers.length - 1];

      if (!lastSummary) return;

      // 计算最后一个月份容器的底部位置
      const lastSummaryBottom = lastSummary.offsetTop + lastSummary.offsetHeight;
      // 容器的滚动高度和可视高度
      const clientHeight = container.clientHeight;
      const scrollTop = container.scrollTop;

      // 当滚动到距离底部200px以内时，加载下一个月份
      if (lastSummaryBottom - scrollTop <= clientHeight + 200) {
        this.loadLock = true; // 加锁防止重复请求
        const nextMonth = this.getPreviousMonth(this.currentEarliestMonth);
        this.currentEarliestMonth = nextMonth;
        this.loadMonthData(nextMonth);
      }
    },

    // 根据文章id显示详情页
    getArticleDetailsData(id) {
      this.articleId = id;// 记录当前文章ID
      this.isDetailsVisible = true;// 显示文章详情
    },

    // 关闭文章详情页
    closeArticleDetails() {
      this.isDetailsVisible = false;
      this.articleId = '';
    },

    // 处理子组件的文章切换事件
    handleArticleChange(newArticleId) {
      this.articleId = newArticleId;
    },

    // 检查路由 query 参数，如果存在 articleId，则自动打开详情
    checkRouteQuery() {
      const articleId = this.$route.query.articleId;
      if (articleId) {
        this.articleId = articleId;
        this.isDetailsVisible = true;
        // 清除路由中的 query 参数，避免刷新页面时重复打开
        this.$router.replace({ query: {} });
      }
    }

  }
}
</script>

<style scoped lang="less">
.page-container {
  padding: 10vh 15px 8vh;
  background: linear-gradient(180deg, #f0f9ff 0%, #ffffff 40%);
  height: 100vh;
  overflow-y: auto;
  box-sizing: border-box;
}

.article-summary {
  margin-bottom: 35px;
}

.month-header {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  gap: 12px;

  .month-divider {
    flex: 1;
    height: 1px;
    background: linear-gradient(90deg, transparent, #cbd5e1, transparent);
    max-width: 100px;
  }

  .month-text {
    font-size: 13px;
    font-weight: 500;
    color: #64748b;
    letter-spacing: 1px;
    padding: 0 10px;
  }
}

.article-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 14px;
}

.article-card {
  background: #ffffff;
  border-radius: 14px;
  overflow: hidden;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: pointer;
  display: flex;
  flex-direction: column;

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
  }

  .article-image-wrapper {
    position: relative;
    width: 100%;
    height: 140px;
    overflow: hidden;

    .article-img {
      width: 100%;
      height: 100%;
      background-size: cover;
      background-repeat: no-repeat;
      background-position: center;
      transition: transform 0.3s ease;

      .image-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: linear-gradient(180deg, transparent 0%, rgba(0, 0, 0, 0.1) 100%);
      }
    }

    .article-category {
      position: absolute;
      top: 10px;
      left: 10px;
      background: rgba(59, 130, 246, 0.9);
      color: #fff;
      padding: 4px 10px;
      border-radius: 12px;
      font-size: 9px;
      font-weight: 600;
      letter-spacing: 0.5px;
      backdrop-filter: blur(4px);
    }
  }

  &:hover .article-img {
    transform: scale(1.05);
  }

  .article-content {
    padding: 14px;
    display: flex;
    flex-direction: column;
    gap: 8px;
    flex: 1;

    .article-title {
      font-size: 13px;
      font-weight: 600;
      color: #1e293b;
      line-height: 1.5;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      text-overflow: ellipsis;
      min-height: 39px;
    }

    .article-author {
      font-size: 11px;
      color: #64748b;
      font-weight: 400;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .article-footer {
      margin-top: auto;
      padding-top: 8px;

      .read-more {
        font-size: 10px;
        color: #3b82f6;
        font-weight: 500;
        display: flex;
        align-items: center;
        gap: 4px;
        transition: all 0.2s ease;

        &::after {
          content: '→';
          transition: transform 0.2s ease;
          margin-left: 4px;
        }
      }
    }
  }

  &:hover .read-more::after {
    transform: translateX(3px);
  }
}

.loading {
  text-align: center;
  padding: 15px;
  font-size: 12px;
  color: #999;
}

.hide-scrollbar {
  -ms-overflow-style: none;
  scrollbar-width: none;

  &::-webkit-scrollbar {
    display: none;
  }
}
</style>